<?php
/**
 * Created by PhpStorm.
 * User: 郑好
 * Date: 2019/4/22
 * Time: 下午6:12
 */

namespace app\common;

use think\Exception;
use Log;

class DingTalk
{
    use InstanceTrait;

    // 钉钉 技术组 推送测试
    public $testJSZ = "https://oapi.dingtalk.com/robot/send?access_token=5da6549ddac7fcc8f1fcd611f0e704f35cb1eef59697e135d3602713fcc51291";
    // $message="这是一条消息推送测试～";
    // $data = [
    // "msgtype" => "text",
    // "text" => [
    // "content" => $message
    // ],
    // "at" => [
    // "atMobiles" => [
    // "15716020283"
    // ],
    // "isAtAll" => false
    // ]
    // ];
    // $data_string = json_encode($data);
    //
    // $result = DingTalk::getInstance()->sendMsgToJSZ(DingTalk::getInstance()->testJSZ, $data_string);

    public function sendMsgToJSZ($remote_server, $post_string)
    {
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $remote_server);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json;charset=utf-8"));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
            if (config("app_env") == "local") {
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            }

            $data = curl_exec($ch);
            curl_close($ch);
            return true;
        } catch (Exception $e) {
            \Log::error("钉钉推送失败：".$post_string . $e->getMessage(), []);
            return false;
        }
    }
}
